package com.kly.sc.api.application.controller.notice;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.consts.Constants;
import com.kly.sc.api.application.controller.notice.resp.NoticeRsp;
import com.kly.sc.api.application.controller.other.request.CommonLogRequest;
import com.kly.sc.api.application.controller.product.request.ProductRequest;
import com.kly.sc.api.application.enums.MsgType;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.sc.api.application.utils.Result;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.app.RequestBasicInfo;
import com.kly.sc.api.infras.enums.RestCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.sc.api.integration.RCClient;
import com.kly.service.GiftEquityService;
import com.kly.service.MemberService;
import com.kly.user.dto.CommonLogReq;
import com.kly.user.dto.UserBaseDto;
import com.kly.user.service.OtherService;
import com.kly.user.service.UserService;
import io.rong.messages.TxtMessage;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 系统通知
 */
@Slf4j
@RestController
@RequestMapping("api/notice")
public class NoticeController extends BaseComponent {

    @Resource
    private MemberService memberService;
    @NacosValue(value = "${meboo.gift.equity.msg}", autoRefreshed = true)
    private String giftingEquityMsg;
    @NacosValue(value = "${meboo.gift.equity.push.msg}", autoRefreshed = true)
    private String giftingEquityPushMsg;
    @NacosValue(value = "${meboo.gift.equity.enable.startDate}", autoRefreshed = true)
    private String startDate;
    @NacosValue(value = "${customer.service.userCode}", autoRefreshed = true)
    private String customerServiceCode;
    @NacosValue(value = "${meboo.gift.equity.enable.switch:false}", autoRefreshed = true)
    private Boolean enableSwitch;
    @Resource
    GiftEquityService giftEquityService;
    @Resource
    UserService userService;
    @Resource
    RCClient rcClient;

    /**
     * 弹窗消息，返回为空时，不弹窗
     */
    @ResponseBody
    @RequestMapping(value = "/giftingEquityMsg")
    public Result<NoticeRsp> QueryProductCategory() {
        if (!enableSwitch) {
            return Result.ok();
        }

        final String currentUserCode = getCurrentUserCode();
        if (StringUtils.isEmpty(currentUserCode)) {
            return Result.ok();
        }

        // ppv打开时不显示
        final Boolean showPPPV = super.showPPPV();
        if (showPPPV) {
            return Result.ok();
        }

        // 指定时间前可以发放权益
        Date effectiveStartDate = DateUtil.parseDateTime(startDate);
        final UserBaseDto userInfo = RpcUtils.getResult(userService.getUserBaseInfo(currentUserCode));
        if (userInfo.getGmtCreate().after(effectiveStartDate)) {
            return Result.ok();
        }

        // 是否已发放
        final Boolean hasEquityGift = RpcUtils.getResult(giftEquityService.hasEquityGift(currentUserCode));
        if (hasEquityGift) {
            return Result.ok();
        }

        // 发送消息
        sendMessage(customerServiceCode, "PRIVATE", currentUserCode, MsgType.TxtMsg.getType(), giftingEquityPushMsg, "");

        // 会员、非会员赠送不同的ppv个数
        final NoticeRsp noticeRsp = JSONUtil.toBean(giftingEquityMsg, NoticeRsp.class);
        final Boolean isMember = RpcUtils.getResult(memberService.haveMemberRecord(currentUserCode));
        if (isMember) {
            giftEquityService.addEquityGiftLog(currentUserCode, true, 2, 2);
            return Result.ok(noticeRsp.setPPV(noticeRsp,2, 2));
        }
        giftEquityService.addEquityGiftLog(currentUserCode, false, 1, 1);
        return Result.ok(noticeRsp.setPPV(noticeRsp,1, 1));
    }

    /**
     * 调用Server api发送消息
     */
    public void sendMessage(String currentUserId, String conversationType, String targetId, String objectName, String content, String pushContent) throws ApplicationException {

        try {
            ResponseResult responseResult = null;
            if (Constants.CONVERSATION_TYPE_PRIVATE.equals(conversationType)) {
                PrivateMessage privateMessage = new PrivateMessage()
                        .setSenderId(currentUserId)
                        // 是否向发件人客户端同步已发消息。1 表示同步 0，即不同步
                        .setIsIncludeSender(1)
                        .setTargetId(new String[]{targetId})
                        .setObjectName(objectName)
                        .setContent(new TxtMessage(content, ""))
                        .setPushContent(pushContent);
                responseResult = rcClient.sendPrivateMessage(privateMessage);
            }


            if (Objects.isNull(responseResult) || responseResult.getCode() != 200) {
                log.error("Send message by IM exception, resultCode={},errorMessage={}", responseResult.getCode(), responseResult.getErrorMessage());
            }
        } catch (ApplicationException e) {
            log.error("sendMessageFailed, userCode:{}", targetId, e);
        }

    }

    public static void main(String[] args) {
        String s = "Dear User, \nMeboo experienced a temporary service interruption due to a server attack. The issue has been resolved, and all services are now restored. We apologize for any inconvenience.\nYour membership benefits and purchased products are unaffected. To thank you and apologize, we are offering you complimentary access to unlock private photos and videos. You can view these benefits under the \"Me\" tab.\nWe hope these gifts enhance your experience and help you find your ideal match on Meboo.\nThank you for your understanding and support.\nSincerely,\nThe Meboo Team";
    }
}
